# coding: utf-8
from functools import wraps
import traceback
from django.http.response import HttpResponseBadRequest, HttpResponseServerError

from analysis.utils import logs


class AnalysisException(Exception):
    pass


class GenericException(AnalysisException):
    def __init__(self, detail):
        self.detail = detail

    def __str__(self):
        return repr(self.detail)


class GenericExceptionNoResponse(AnalysisException):
    def __init__(self, detail):
        self.detail = detail

    def __str__(self):
        return repr(self.detail)


def catch_exception(func):
    """
    抓取异常的装饰器，统一抓取抛出的异常，处理记录日志并返回结果。
    :param func:
    :return Response:
    """

    @wraps(func)
    def deco(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except GenericException as e:
            if isinstance(e.detail, dict) and "info" in e.detail.keys():
                # 记录到日志中。
                logs.log.format_log(e.detail.get("info", None))

                if "info" in e.detail.keys():
                    e.detail.pop("info")

            return HttpResponseBadRequest()
        except GenericExceptionNoResponse as e:
            # 记录日志但不返回Response
            if isinstance(e.detail, dict):
                logs.log.format_log(e.detail.get("info", None))
        except (AnalysisException, Exception):
            logs.log_ex.format_log(traceback.format_exc())
            return HttpResponseServerError()

    return deco
